package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;


@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String fileUpload(MultipartFile file) {
        try {
            MinioClient minioClient = MinioClient.builder().endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
            boolean bucketExists
                    = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            //检查桶是否存在
            if (bucketExists) {
                System.out.println("Bucket " + minioProperties.getBucketName() + " already exists.");
            } else {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //获取文件上传日期
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            //随机生成UUID作为文件名
            String prefix = UUID.randomUUID().toString().replaceAll("-", "");
            //获取新的文件名
            String fileName = format + "/" + prefix + suffix;
            //获取流对象
            InputStream is = file.getInputStream();
            //获取文件大小
            long size = file.getSize();
            //获取文件的mime类型
            String type = file.getContentType();

            //创建PutObjectArgs对象
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fileName)
                    .stream(is, size, -1)
                    .contentType(type)
                    .build();
            //使用putObject上传文件到Minio服务器的桶中
            minioClient.putObject(putObjectArgs);

            return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }
        return null;
    }
}
